package com.wing.storage.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.chanjet.entity.material.MaterialCreateRequest;
import com.wing.chanjet.entity.material.MaterialRdrecordDetailsRequest;
import com.wing.chanjet.entity.sales.SalesCreateRequest;
import com.wing.chanjet.entity.sales.SalesRdrecordDetailsRequest;
import com.wing.chanjet.feign.ChanjetClient;
import com.wing.common.utils.JsonResult;
import com.wing.enums.MoveDownWarehouseStatusEnum;
import com.wing.platform.order.model.entity.Warehouse;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.WarehouseShelfSpaceDao;
import com.wing.purchase.model.entity.WarehouseShelfSpace;
import com.wing.purchase.model.request.PurchaseSkuItermOutForm;
import com.wing.purchase.util.PurchaseSignUtil;
import com.wing.res.MoveDownWarehouseIFeign;
import com.wing.res.dao.ReceiptRecordDao;
import com.wing.res.dao.ReceiptRecordDetailDao;
import com.wing.res.model.entity.ReceiptRecord;
import com.wing.res.model.entity.ReceiptRecordDetail;
import com.wing.sell.dao.CustomersInfoDao;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.storage.dao.*;
import com.wing.storage.model.entity.*;
import com.wing.storage.model.response.PurchaseOutDetailExportVO;
import com.wing.storage.model.response.PurchaseOutDetailInfoExportVO;
import com.wing.storage.model.response.PurchaseOutExportVO;
import com.wing.utils.GenerateNumberUtils;
import com.wing.visual.dao.WarehouseDao;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 仓库产品出库作业-ServiceImpl
 *
 * @author xiayang
 */
@Service
@Slf4j
public class ProductStorageWorkOutServiceImpl extends ServiceImpl<ProductStorageWorkOutDao, ProductStorageWorkOut> implements ProductStorageWorkOutService {

    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private ProductStorageWorkOutDetailService productStorageWorkOutDetailService;
    @Autowired
    private ProductInventoryDetailService productInventoryDetailService;
    @Autowired
    private ChanjetClient chanjetClient;
    @Autowired
    private CustomersInfoDao customersInfoDao;
    @Autowired
    private ProductInventoryDetailDao productInventoryDetailDao;
    @Resource
    private ReceiptRecordDao receiptRecordDao;
    @Autowired
    private WarehouseDao warehouseDao;
    @Autowired
    private PalletBoxSkuItermDao palletBoxSkuItermDao;
    @Autowired
    private WarehouseAreaSkuItermDao warehouseAreaSkuItermDao;
    @Autowired
    private WarehouseShelfSpaceDao warehouseShelfSpaceDao;
    @Resource
    private ProductInventoryService productInventoryService;
    @Resource
    private ReceiptRecordDetailDao receiptRecordDetailDao;
    @Resource
    private ProductStorageWorkOutDetailDao productStorageWorkOutDetailDao;
    //    @Resource
//    private RedisHelperImpl redisHelper;
    @Autowired
    private MoveDownWarehouseIFeign moveDownWarehouseIFeign;
    
    @Override
    public Page<ProductStorageWorkOut> pageList(Page page, Map<String, Object> params) {
        //仓库产品出库作业详细列表 22222
        Map<String, Object> detailParams = new HashMap<>();
        List<ProductStorageWorkOutDetail> detailList = productStorageWorkOutDetailService.list(detailParams);
        //仓库产品出库作业列表
        List<ProductStorageWorkOut> list = baseMapper.pageList(page, params);
        for (ProductStorageWorkOut productStorageWorkOut : list) {
            List<ProductStorageWorkOutDetail> details = detailList.stream()
                    .filter(t -> t.getProductStorageWorkOutId() != null && t.getProductStorageWorkOutId().equals(productStorageWorkOut.getId()))
                    .collect(Collectors.toList());
            productStorageWorkOut.setProductStorageWorkOutDetailList(details);
        }
        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional(readOnly = false)
    public JsonResult add(ProductStorageWorkOut productStorageWorkOut) {
        //查询对应其他出库的需要出库多少
        //查询已经出库了多少
        //todo 出库详情 记录领料ID 和 对应skuId      每次出库前校验当前sku已经出库了多少    查询应该出库多少


        List<ProductStorageWorkOutDetail> productStorageWorkOutDetailList = productStorageWorkOut.getProductStorageWorkOutDetailList();

        // 1. 校验出库数量是否大于0
        for (ProductStorageWorkOutDetail r2 : productStorageWorkOutDetailList) {
            if (r2.getOutNum().compareTo(BigDecimal.ZERO) <= 0) {
                return JsonResult.fail("数量为0！！！");
            }
        }

        // 2. 查询该订单之前已经出库的数量
        LambdaQueryWrapper<ReceiptRecordDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReceiptRecordDetail::getReceiptRecordId, productStorageWorkOut.getReceiptRecordId());
        List<ReceiptRecordDetail> receiptRecordDetail = receiptRecordDetailDao.selectList(lambdaQueryWrapper);

        if (receiptRecordDetail.isEmpty()) {
            return JsonResult.fail("无出库信息");
        }

        // 3. 查询历史已出库数量
        List<ProductStorageWorkOutDetail> productStorageWorkOutDetails2 = productStorageWorkOutDetailDao.selProductStorageNumList(productStorageWorkOut.getReceiptRecordId());

        // 4. 构建已出库数量的映射表
        Map<Long, BigDecimal> existedOutNumMap = new HashMap<>();
        for (ProductStorageWorkOutDetail detail : productStorageWorkOutDetails2) {
            existedOutNumMap.put(
                detail.getProductDetailId(),
                detail.getOutNum()
            );
        }

        // 5. 检查每项是否超发（注意：这里不修改原始 list）
        for (ProductStorageWorkOutDetail r2 : productStorageWorkOutDetailList) {
            BigDecimal currentOutNum = r2.getOutNum();
            BigDecimal existedOutNum = existedOutNumMap.getOrDefault(r2.getProductDetailId(), BigDecimal.ZERO);
            BigDecimal totalOutNum = currentOutNum.add(existedOutNum);

            // 匹配计划领料数
            boolean found = false;
            for (ReceiptRecordDetail recordDetail : receiptRecordDetail) {
                if (recordDetail.getProductDetailId().equals(r2.getProductDetailId())) {
                    if (totalOutNum.compareTo(recordDetail.getReceiptNum()) > 0) {
                        return JsonResult.fail("出库数量超出！！！");
                    }
                    found = true;
                    break;
                }
            }

            if (!found) {
                return JsonResult.fail("找不到对应信息");
            }
        }

        //TODO 出库作业校验提前
        //新增仓库产品出库作业
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String code = dynamicService.getMaxCode("code", "pro_product_storage_work_out");
        String day = simpleDateFormat.format(new Date());
        productStorageWorkOut.setCode("PO" + day + code);
        productStorageWorkOut.setCreateTime(LocalDateTime.now());
        productStorageWorkOut.setCreator(JwtUtils.getLoginUserId());
        productStorageWorkOut.setCreatorName(JwtUtils.getLoginNickname());
        productStorageWorkOut.setExternalCode(GenerateNumberUtils.getOutWorkNumber());

        List<ProductStorageWorkOutDetail> detailList2 = productStorageWorkOut.getProductStorageWorkOutDetailList();
        for (ProductStorageWorkOutDetail productStorageWorkOutDetail : detailList2) {
            //处理完就移除key
            /*     redisHelper.remove("order-out-"+productStorageWorkOut.getReceiptRecordId());*/

            if (productStorageWorkOutDetail.getWarehouseShelfSpaceId() == null) {
                /*throw new BusinessException("出库库位/料箱物料不存在");*/
                return JsonResult.fail("出库库位/料箱物料不存在");
            }

            QueryWrapper<ProductInventory> inventoryQueryWrapper = new QueryWrapper<ProductInventory>();
            inventoryQueryWrapper.eq("product_detail_id", productStorageWorkOutDetail.getProductDetailId());
            ProductInventory productInventory = productInventoryService.getOne(inventoryQueryWrapper);
            if (productInventory == null) {
                /*      throw new BusinessException("出库物料不存在");*/
                return JsonResult.fail("出库物料不存在");
            }

            QueryWrapper<ProductInventoryDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("product_detail_id", productStorageWorkOutDetail.getProductDetailId());
            detailQueryWrapper.eq("product_inventory_id", productInventory.getId());
            detailQueryWrapper.eq("warehouse_id", productStorageWorkOutDetail.getWarehouseId());
            detailQueryWrapper.eq("warehouse_shelf_space_id", productStorageWorkOutDetail.getWarehouseShelfSpaceId());

            WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceDao.selectById(productStorageWorkOutDetail.getWarehouseShelfSpaceId());
            if (warehouseShelfSpace != null) {
                if (warehouseShelfSpace.getWarehouseAreaId() != null) {
                    detailQueryWrapper.eq("warehouse_area_id", warehouseShelfSpace.getWarehouseAreaId());
                }
            }


            if (productStorageWorkOutDetail.getPalletBoxId() != null) {
                detailQueryWrapper.eq("pallet_box_id", productStorageWorkOutDetail.getPalletBoxId());
            }

            List<ProductInventoryDetail> productInventoryDetail02 = productInventoryDetailDao.selectList(detailQueryWrapper);
            // ProductInventoryDetail productInventoryDetail0 = productInventoryDetailDao.selectOne(detailQueryWrapper);
            if (productInventoryDetail02 != null && productInventoryDetail02.size() > 0) {
                BigDecimal totalNum = productInventoryDetail02.stream()
                    .map(ProductInventoryDetail::getQuantity) // 获取每个 ProductInventoryDetail 对象的 num 字段
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 使用 reduce 方法进行求和，初始值为 BigDecimal.ZERO
                if (productStorageWorkOutDetail.getOutNum().compareTo(totalNum) == 1) {
                    return JsonResult.fail("出库库位/料箱物料不足，无法出库");
                }
            } else {
                return JsonResult.fail("出库库位/料箱物料不存在");
            }
        }
        baseMapper.insert(productStorageWorkOut);
        //新增仓库产品出库作业详细
        List<ProductStorageWorkOutDetail> detailList = productStorageWorkOut.getProductStorageWorkOutDetailList();
        for (ProductStorageWorkOutDetail productStorageWorkOutDetail : detailList) {
            productStorageWorkOutDetail.setProductStorageWorkOutId(productStorageWorkOut.getId());
            productStorageWorkOutDetail.setCreateTime(LocalDateTime.now());
            productStorageWorkOutDetail.setCreator(JwtUtils.getLoginUserId());
            productStorageWorkOutDetail.setCreatorName(JwtUtils.getLoginNickname());
            productStorageWorkOutDetail.setReceiptRecordId(productStorageWorkOut.getReceiptRecordId());
            productStorageWorkOutDetail.setWarehouseId(productStorageWorkOutDetail.getWarehouseId());
            productStorageWorkOutDetailService.save(productStorageWorkOutDetail);
            //产品库存-出库
            ProductInventoryDetail productInventoryDetail = new ProductInventoryDetail();
            productInventoryDetail.setInoutType(productStorageWorkOut.getOutTypeId());
            productInventoryDetail.setInoutWorkJob(productStorageWorkOutDetail.getId());
            productInventoryDetail.setProductDetailId(productStorageWorkOutDetail.getProductDetailId());
            productInventoryDetail.setWarehouseId(productStorageWorkOutDetail.getWarehouseId());
            productInventoryDetail.setWarehouseShelfSpaceId(productStorageWorkOutDetail.getWarehouseShelfSpaceId());
            productInventoryDetail.setPalletBoxId(productStorageWorkOutDetail.getPalletBoxId());
            productInventoryDetail.setQuantity(productStorageWorkOutDetail.getOutNum());
            WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceDao.selectById(productInventoryDetail.getWarehouseShelfSpaceId());
            if (warehouseShelfSpace != null) {
                productInventoryDetail.setWarehouseShelfId(warehouseShelfSpace.getShelfId());
                productInventoryDetail.setWarehouseAreaId(warehouseShelfSpace.getWarehouseAreaId());
            }
            //todo匹配库区出来 用库位
            productInventoryDetailService.productOutStorage(productInventoryDetail);
            //TODO 调用本地 料箱存货明细和库位存货明细 扣减库存
            PurchaseSkuItermOutForm purchaseSkuItermOutForm = new PurchaseSkuItermOutForm();
            purchaseSkuItermOutForm.setSkuName(productStorageWorkOutDetail.getSkuName());
            purchaseSkuItermOutForm.setSkuCode(productStorageWorkOutDetail.getSkuCode());
            purchaseSkuItermOutForm.setWarehouseId(productStorageWorkOutDetail.getWarehouseId());
            purchaseSkuItermOutForm.setWarehouseAreaId(warehouseShelfSpace.getWarehouseAreaId());
            purchaseSkuItermOutForm.setWarehouseShelfSpaceId(productStorageWorkOutDetail.getWarehouseShelfSpaceId());
            purchaseSkuItermOutForm.setPalletBoxId(productStorageWorkOutDetail.getPalletBoxId());
            purchaseSkuItermOutForm.setNum(productStorageWorkOutDetail.getOutNum());
            purchaseSkuItermOutForm.setWarehouseShelfId(warehouseShelfSpace.getShelfId());
            reducePurchasePalletBoxAndAreaSkuIterm(purchaseSkuItermOutForm);
        }
        //如果 计划出库数量=已经领取数量 则修改对应状态为 领取完成
        LambdaQueryWrapper<ReceiptRecordDetail> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        // 使用lambda表达式指定实体类的属性
        lambdaQueryWrapper2.eq(ReceiptRecordDetail::getReceiptRecordId, productStorageWorkOut.getReceiptRecordId());
        //其他出库 看看出库数量计划是多少
        List<ReceiptRecordDetail> receiptRecordDetail2 = receiptRecordDetailDao.selectList(lambdaQueryWrapper2);
        if (receiptRecordDetail2.size() > 0) {
            // 查看已经领取的数量
            List<ProductStorageWorkOutDetail> productStorageWorkOutDetails = productStorageWorkOutDetailDao.selProductStorageNumList(productStorageWorkOut.getReceiptRecordId());
            for (ReceiptRecordDetail recordDetail : receiptRecordDetail2) {
                for (ProductStorageWorkOutDetail productStorageWorkOutDetail : productStorageWorkOutDetails) {
                    if (recordDetail.getProductDetailId().equals(productStorageWorkOutDetail.getProductDetailId())) {
                        BigDecimal outNumRp = recordDetail.getReceiptNum();
                        if (outNumRp.compareTo(productStorageWorkOutDetail.getOutNum()) == 0) {
                            //更新明细
                            recordDetail.setFlagStatus("2");
                            receiptRecordDetailDao.updateById(recordDetail);
                            //更新主表
                            ReceiptRecord receiptRecord = new ReceiptRecord();
                            receiptRecord.setFlagStatus("2");
                            receiptRecord.setStatus(3);
                            receiptRecord.setId(Integer.valueOf(productStorageWorkOut.getReceiptRecordId().toString()));
                            receiptRecordDao.updateById(receiptRecord);
                            ReceiptRecord record = receiptRecordDao.selectById(receiptRecord.getId());
                            //更新调拨
                            if (record.getInventoryTypeId() == 2L) {//为调拨出库
                                Map<String, Object> param = new HashMap<>();
                                param.put("id", record.getWorkOrderId());
                                param.put("status", MoveDownWarehouseStatusEnum.wait_in.getCode());
                                moveDownWarehouseIFeign.updateMoveDownWareHouseMapById(param);
                                //更新明细
                                Map<String, Object> param2 = new HashMap<>();
                                param2.put("id", record.getWorkOrderId());
                                param2.put("skuId", recordDetail.getProductDetailId());
                                param2.put("status", MoveDownWarehouseStatusEnum.wait_in.getCode());
                                moveDownWarehouseIFeign.updateMoveDownWareHouseItemByMap(param2);
                            }
                        }
                    }
                }
            }
        }
        try {
            //处理完就移除key
            /*   redisHelper.remove("order-out-"+productStorageWorkOut.getReceiptRecordId());*/
            if (productStorageWorkOut.getOutTypeCode().equals(PurchaseSignUtil.CPC)) {
                //todo 畅捷通销售出库数据   成品销售出库
                addCjtDoWorkOut(productStorageWorkOut);
            } else if (productStorageWorkOut.getOutTypeCode().equals(PurchaseSignUtil.SCC)) {
                //todo  材料出库
                materialOutInfo(productStorageWorkOut);
            }


        } catch (Exception e) {
            log.info("采购入库失败:", e);
            e.printStackTrace();
        }
        return JsonResult.success();
     }

    @Override
    public void update(ProductStorageWorkOut productStorageWorkOut) {
        //更新仓库产品出库作业
        productStorageWorkOut.setUpdateTime(LocalDateTime.now());
        productStorageWorkOut.setModifier(JwtUtils.getLoginUserId());
        productStorageWorkOut.setModifierName(JwtUtils.getLoginNickname());
        baseMapper.updateById(productStorageWorkOut);
        //删除仓库产品出库作业详细
        productStorageWorkOutDetailService.remove(Wrappers.<ProductStorageWorkOutDetail>query().lambda().eq(ProductStorageWorkOutDetail::getProductStorageWorkOutId, productStorageWorkOut.getId()));
        //新增仓库产品出库作业详细
        List<ProductStorageWorkOutDetail> detailList = productStorageWorkOut.getProductStorageWorkOutDetailList();
        for (ProductStorageWorkOutDetail productStorageWorkOutDetail : detailList) {
            productStorageWorkOutDetail.setProductStorageWorkOutId(productStorageWorkOut.getId());
            productStorageWorkOutDetail.setCreateTime(LocalDateTime.now());
            productStorageWorkOutDetail.setCreator(JwtUtils.getLoginUserId());
            productStorageWorkOutDetail.setCreatorName(JwtUtils.getLoginNickname());
        }
        productStorageWorkOutDetailService.saveBatch(detailList);
    }

    @Override
    public void del(Long productStorageWorkOutId) {
        ProductStorageWorkOut productStorageWorkOut = baseMapper.get(productStorageWorkOutId);
        //删除仓库产品出库作业详细
        productStorageWorkOutDetailService.remove(Wrappers.<ProductStorageWorkOutDetail>query().lambda().eq(ProductStorageWorkOutDetail::getProductStorageWorkOutId, productStorageWorkOut.getId()));
        //删除仓库产品出库作业
        baseMapper.deleteById(productStorageWorkOutId);
    }

    @Override
    public ProductStorageWorkOut get(Long productStorageWorkOutId) {
        return baseMapper.get(productStorageWorkOutId);
    }

    @Override
    public Page<ProductStorageWorkOutDetail> getProductStorageWorkOutDetail(Page page, Map<String, Object> params) {
        page.setRecords(productStorageWorkOutDetailDao.getProductStorageWorkOutDetail(page,params));
        return page;
    }

    @Override
    public Page<ProductStorageWorkOutDetailStatic> getProductStorageWorkOutDetailStatic(Page page, Map<String, Object> params) {
        page.setRecords(productStorageWorkOutDetailDao.getProductStorageWorkOutDetailStatic(page,params));
        return page;
    }

    @Override
    public List<PurchaseOutDetailExportVO> exportProductStorageWorkOutDetailStatic(Map<String, Object> params) {
        return productStorageWorkOutDetailDao.exportProductStorageWorkOutDetailStatic(params);
    }

    @Override
    public List<PurchaseOutDetailInfoExportVO> exportProductStorageWorkOutDetail(Map<String, Object> params) {
        return productStorageWorkOutDetailDao.exportProductStorageWorkOutDetail(params);
    }

    @Override
    public List<PurchaseOutExportVO> exportProductStoragePageList(Map<String, Object> params) {
        return baseMapper.exportProductStoragePageList(params);
    }

    /**
     * 扣减库存
     * @param purchaseSkuItermOutForm
     */
    public void reducePurchasePalletBoxAndAreaSkuIterm(PurchaseSkuItermOutForm purchaseSkuItermOutForm){
        Warehouse warehouse = warehouseDao.selectById(purchaseSkuItermOutForm.getWarehouseId());
        if(warehouse!=null){
            // 0 是 1 否
            if(warehouse.getWorkbinStatus()!=null){

                if(warehouse.getWorkbinStatus()==1L){
                    //扣减 库位存货明细
                    reducePurchaseAreaSkuIterm(purchaseSkuItermOutForm);
                }else{

                    PalletBoxSkuIterm palletBoxSkuIterm=new PalletBoxSkuIterm();
                    palletBoxSkuIterm.setSkuName(purchaseSkuItermOutForm.getSkuName());
                    palletBoxSkuIterm.setSkuCode(purchaseSkuItermOutForm.getSkuCode());
                    palletBoxSkuIterm.setWarehouseShelfSpaceId(purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
                    palletBoxSkuIterm.setWarehouseId(purchaseSkuItermOutForm.getWarehouseId());
                    palletBoxSkuIterm.setWarehouseAreaId(purchaseSkuItermOutForm.getWarehouseAreaId());
                    palletBoxSkuIterm.setNum(purchaseSkuItermOutForm.getNum());
                    palletBoxSkuIterm.setPalletBoxId(purchaseSkuItermOutForm.getPalletBoxId());


                    QueryWrapper<PalletBoxSkuIterm> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("sku_code", purchaseSkuItermOutForm.getSkuCode());
                    detailQueryWrapper.eq("warehouse_id", purchaseSkuItermOutForm.getWarehouseId());
                    detailQueryWrapper.eq("warehouse_area_id", purchaseSkuItermOutForm.getWarehouseAreaId());
                    detailQueryWrapper.eq("warehouse_shelf_space_id", purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
                    detailQueryWrapper.eq("pallet_box_id", purchaseSkuItermOutForm.getPalletBoxId()==null?0L:purchaseSkuItermOutForm.getPalletBoxId());


                    PalletBoxSkuIterm palletBoxSkuIterm2 = palletBoxSkuItermDao.selectOne(detailQueryWrapper);
                    if(palletBoxSkuIterm2!=null){
                        palletBoxSkuIterm2.setNum(palletBoxSkuIterm2.getNum().subtract(purchaseSkuItermOutForm.getNum()));
                        palletBoxSkuItermDao.updateById(palletBoxSkuIterm2);
                    }

                    //同时扣减存货明细数据
                    reducePurchaseAreaSkuIterm(purchaseSkuItermOutForm);

                }
            }else{
                PalletBoxSkuIterm palletBoxSkuIterm=new PalletBoxSkuIterm();
                palletBoxSkuIterm.setSkuName(purchaseSkuItermOutForm.getSkuName());
                palletBoxSkuIterm.setSkuCode(purchaseSkuItermOutForm.getSkuCode());
                palletBoxSkuIterm.setWarehouseShelfSpaceId(purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
                palletBoxSkuIterm.setWarehouseId(purchaseSkuItermOutForm.getWarehouseId());
                palletBoxSkuIterm.setWarehouseAreaId(purchaseSkuItermOutForm.getWarehouseAreaId());
                palletBoxSkuIterm.setNum(purchaseSkuItermOutForm.getNum());
                palletBoxSkuIterm.setPalletBoxId(purchaseSkuItermOutForm.getPalletBoxId());


                QueryWrapper<PalletBoxSkuIterm> detailQueryWrapper = new QueryWrapper<>();
                detailQueryWrapper.eq("sku_code", purchaseSkuItermOutForm.getSkuCode());
                detailQueryWrapper.eq("warehouse_id", purchaseSkuItermOutForm.getWarehouseId());
                detailQueryWrapper.eq("warehouse_area_id", purchaseSkuItermOutForm.getWarehouseAreaId());
                detailQueryWrapper.eq("warehouse_shelf_space_id", purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
                detailQueryWrapper.eq("pallet_box_id", purchaseSkuItermOutForm.getPalletBoxId()==null?0L:purchaseSkuItermOutForm.getPalletBoxId());


                PalletBoxSkuIterm palletBoxSkuIterm2 = palletBoxSkuItermDao.selectOne(detailQueryWrapper);
                if(palletBoxSkuIterm2!=null){
                    palletBoxSkuIterm2.setNum(palletBoxSkuIterm2.getNum().subtract(purchaseSkuItermOutForm.getNum()));
                    palletBoxSkuItermDao.updateById(palletBoxSkuIterm2);
                }

                //同时扣减存货明细数据
                reducePurchaseAreaSkuIterm(purchaseSkuItermOutForm);
            }

        }

    }


    /**
     * 扣减存货明细数据
     * @param purchaseSkuItermOutForm
     */
    public void reducePurchaseAreaSkuIterm(PurchaseSkuItermOutForm purchaseSkuItermOutForm){
        WarehouseAreaSkuIterm warehouseAreaSkuIterm=new WarehouseAreaSkuIterm();
        warehouseAreaSkuIterm.setSkuName(purchaseSkuItermOutForm.getSkuName());
        warehouseAreaSkuIterm.setSkuCode(purchaseSkuItermOutForm.getSkuCode());
        warehouseAreaSkuIterm.setWarehouseShelfSpaceId(purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
        warehouseAreaSkuIterm.setWarehouseId(purchaseSkuItermOutForm.getWarehouseId());
        warehouseAreaSkuIterm.setWarehouseAreaId(purchaseSkuItermOutForm.getWarehouseAreaId());
        warehouseAreaSkuIterm.setNum(purchaseSkuItermOutForm.getNum());

        QueryWrapper<WarehouseAreaSkuIterm> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper.eq("sku_code", purchaseSkuItermOutForm.getSkuCode());
        detailQueryWrapper.eq("warehouse_id", purchaseSkuItermOutForm.getWarehouseId());
        detailQueryWrapper.eq("warehouse_area_id", purchaseSkuItermOutForm.getWarehouseAreaId());
        detailQueryWrapper.eq("warehouse_shelf_space_id", purchaseSkuItermOutForm.getWarehouseShelfSpaceId());
        WarehouseAreaSkuIterm warehouseAreaSkuIterm1 = warehouseAreaSkuItermDao.selectOne(detailQueryWrapper);

        if(warehouseAreaSkuIterm1!=null){
            warehouseAreaSkuIterm1.setNum(warehouseAreaSkuIterm1.getNum().subtract(purchaseSkuItermOutForm.getNum()));
            warehouseAreaSkuItermDao.updateById(warehouseAreaSkuIterm1);
        }

    }



    /**
     * 畅捷通出库作业
     * @param productStorageWorkOut
     */
    public void addCjtDoWorkOut(ProductStorageWorkOut productStorageWorkOut){
        try {
            SalesCreateRequest salesCreateRequest = new SalesCreateRequest();

            List<SalesRdrecordDetailsRequest> rdrecordDetailsRequestList=new ArrayList<>();

            //新增仓库产品出库作业详细
            List<ProductStorageWorkOutDetail> detailList = productStorageWorkOut.getProductStorageWorkOutDetailList();
            for (ProductStorageWorkOutDetail productStorageWorkOutDetail : detailList) {
                //todo 组装存货数据 存储到畅捷通
                SalesRdrecordDetailsRequest salesRdrecordDetailsRequest = new SalesRdrecordDetailsRequest();
                SalesRdrecordDetailsRequest.InventoryRequest inventoryRequest= salesRdrecordDetailsRequest.new InventoryRequest();
                inventoryRequest.setCode(productStorageWorkOutDetail.getSkuCode());
                salesRdrecordDetailsRequest.setInventory(inventoryRequest);
                salesRdrecordDetailsRequest.setBaseQuantity(productStorageWorkOutDetail.getOutNum());
                rdrecordDetailsRequestList.add(salesRdrecordDetailsRequest);
            }

            salesCreateRequest.setExternalCode(productStorageWorkOut.getExternalCode());
            /*salesCreateRequest.setCode();*/
            CustomersInfo customersInfo = customersInfoDao.selectById(productStorageWorkOut.getCustomerId());
            if(customersInfo!=null){
                SalesCreateRequest.PartnerRequest partnerRequest = salesCreateRequest.new PartnerRequest();
                partnerRequest.setCode(customersInfo.getCode());
                salesCreateRequest.setPartner(partnerRequest);
            }

            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String workDate = simpleDateFormat2.format(new Date());
            salesCreateRequest.setVoucherDate(workDate);


            SalesCreateRequest.PurchaseVoucherTypeRequest purchaseVoucherTypeRequest=salesCreateRequest.new PurchaseVoucherTypeRequest();
            purchaseVoucherTypeRequest.setCode("ST1021");
            salesCreateRequest.setVoucherType(purchaseVoucherTypeRequest);


            SalesCreateRequest.PurchaseBusiTypeRequest purchaseBusiTypeRequest=salesCreateRequest.new PurchaseBusiTypeRequest();
            purchaseBusiTypeRequest.setCode("15");
            salesCreateRequest.setBusiType(purchaseBusiTypeRequest);

            SalesCreateRequest.WarehouseRequest warehouseRequest= salesCreateRequest.new WarehouseRequest();
            Long warehouseId = productStorageWorkOut.getWarehouseId();
            if(warehouseId!=null){
                Warehouse warehouse = warehouseDao.selectById(warehouseId);
                if(warehouse!=null){
                    warehouseRequest.setCode(warehouse.getCode());
                    warehouseRequest.setName(warehouse.getName());
                }
            }
            salesCreateRequest.setWarehouse(warehouseRequest);
            salesCreateRequest.setMemo("出库作业操作进入系统");
            salesCreateRequest.setRes(rdrecordDetailsRequestList);
            salesCreateRequest.setRDRecordDetails(rdrecordDetailsRequestList);

            //todo 调用畅捷通进行出库 销售出库
            JsonResult jsonResult = chanjetClient.syncOutSalesDispatch(salesCreateRequest);

            //领料出库


            log.info("畅捷通销售出库调用成功：",jsonResult);
        }catch (Exception e){
            e.printStackTrace();
            log.info("畅捷通销售出库数据出现异常：",e);
        }
    }


    /**
     * 材料出库
     * @param productStorageWorkOut
     */
    public void materialOutInfo(ProductStorageWorkOut productStorageWorkOut){
        //领料出库-材料出库
        try{
            MaterialCreateRequest materialCreateRequest=new MaterialCreateRequest();
            materialCreateRequest.setExternalCode(productStorageWorkOut.getExternalCode());

            MaterialCreateRequest.PurchaseVoucherTypeRequest purchaseVoucherTypeRequest=materialCreateRequest.new PurchaseVoucherTypeRequest();
            purchaseVoucherTypeRequest.setCode("ST1022");

            materialCreateRequest.setVoucherType(purchaseVoucherTypeRequest);


            MaterialCreateRequest.PurchaseBusiTypeRequest purchaseBusiTypeRequest=materialCreateRequest.new PurchaseBusiTypeRequest();
            purchaseBusiTypeRequest.setCode("41");
            materialCreateRequest.setBusiType(purchaseBusiTypeRequest);

            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            String workDate = simpleDateFormat2.format(new Date());
            materialCreateRequest.setVoucherDate(workDate);


            MaterialCreateRequest.WarehouseRequest warehouseRequest= materialCreateRequest.new WarehouseRequest();
            Long warehouseId = productStorageWorkOut.getWarehouseId();
            if(warehouseId!=null){
                Warehouse warehouse = warehouseDao.selectById(warehouseId);
                if(warehouse!=null){
                    warehouseRequest.setCode(warehouse.getCode());
                    warehouseRequest.setName(warehouse.getName());
                }
            }

            materialCreateRequest.setWarehouse(warehouseRequest);

            materialCreateRequest.setMemo("外部接口-添加领料进入数据");

            List<MaterialRdrecordDetailsRequest> rdrecordDetailsRequestList=new ArrayList<>();


            List<ProductStorageWorkOutDetail> receiptRecordDetailList = productStorageWorkOut.getProductStorageWorkOutDetailList();
            for (ProductStorageWorkOutDetail receiptRecordDetail : receiptRecordDetailList) {
                MaterialRdrecordDetailsRequest rdrecordDetailsRequest=new MaterialRdrecordDetailsRequest();

                MaterialRdrecordDetailsRequest.InventoryRequest inventoryRequest= rdrecordDetailsRequest.new InventoryRequest();
                inventoryRequest.setCode(receiptRecordDetail.getSkuCode());
                inventoryRequest.setName(receiptRecordDetail.getSkuName());

                rdrecordDetailsRequest.setInventory(inventoryRequest);
                rdrecordDetailsRequest.setBaseQuantity(receiptRecordDetail.getOutNum());

                rdrecordDetailsRequestList.add(rdrecordDetailsRequest);

            }
            materialCreateRequest.setRes(rdrecordDetailsRequestList);
            materialCreateRequest.setRDRecordDetails(rdrecordDetailsRequestList);

            JsonResult jsonResult = chanjetClient.syncAddMaterialDispatch(materialCreateRequest);
            log.info(String.valueOf(jsonResult));

        }catch (Exception e){
            //e.printStackTrace();
            log.info("出库作业-领料出库异常："+e);
        }

    }



}
